#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <poll.h>

char rbuf[100] = {0};
char *wstr = "123456789123456789\r\n";

int main(int argc, char *argv[])
{
	int fd;
	int i;
	int ret;
	int is_read;
	struct pollfd  fds[1];
	
	if((argc >= 2) && (strncmp(argv[1], "read", 4) == 0))
		is_read = 1;
	else
		is_read = 0;

	fd = open("/dev/poll", O_RDWR|O_NONBLOCK);
	if(fd == -1)
	{
		perror("error");
		return -1;
	}

	fds[0].fd = fd;
	if(is_read == 1)
		fds[0].events = POLLIN;
	else
		fds[0].events = POLLOUT;
	fds[0].revents = 0;

	while(1)
	{
		ret = poll(fds, 1, -1);
		if(ret == -1)
			break;

		//判断是否发生读事件
		if(fds[0].revents & POLLIN)
		{
			memset(rbuf, 0, 100);
			ret = read(fd, rbuf, 99);
			if(ret <= 0)
				break;
			printf("%s", rbuf);
			fflush(stdout);
		}

		//判断是否发生写事件
		if(fds[0].revents & POLLOUT)
		{
			ret = write(fd, wstr, strlen(wstr));
			if(ret <= 0)
				break;
		}
	}

	close(fd);

	return 0;
}
